<?php declare(strict_types=1);
/**
 * @author      xianganyall <xianganyall@gmail.com>
 * @copyright   2023-2025 owner
 **/

namespace Srv\Libs\Storage;

abstract class DataStorageAbstract
{
    protected static array $tagObjectList                   = [];           // TAG对象列表
    private const TAG_DEFAULT_NAME                          = 'NULL';       // TAG默认名

    /**
     * @param string $groupName
     * @param string $persistentId
     * @param string $tagName
     * @return mixed
     * 对象获取
     */
    abstract public static function tag(string $groupName, string $persistentId, string $tagName);

    /**
     * @param string $tagStr
     * @param string $className
     * @return string
     * 获取Tag名称
     */
    private static function getTagName(string $tagStr, string $className):string
    {
        return $className.(strlen($tagStr) < 1 ? self::TAG_DEFAULT_NAME : $tagStr);
    }

    /**
     * @param string $tagStr
     * @param array $constructData
     * @return mixed
     * 获取标签的对象
     */
    final protected static function tagGet(string $tagStr, array $constructData)
    {
        $__class__      = static::class;
        $tagName        = self::getTagName($tagStr, $__class__);
        if(isset(self::$tagObjectList[$tagName])) return self::$tagObjectList[$tagName];
        $tagObject                      = new $__class__(...$constructData);
        self::$tagObjectList[$tagName]  = $tagObject;
        return self::$tagObjectList[$tagName];
    }

    /**
     * @param string $tagStr
     * @return bool
     * 删除标签的对象
     */
    final public static function tagDelete(string $tagStr):bool
    {
        $__class__      = static::class;
        $tagName        = self::getTagName($tagStr, $__class__);
        if(isset(self::$tagObjectList[$tagName])){
            unset(self::$tagObjectList[$tagName]);
            return !isset(self::$tagObjectList[$tagName]);
        }
        return true;
    }

    /**
     * 清除全部的对象
     */
    final public static function tagClear():void
    {
        self::$tagObjectList    = [];
    }
}